﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace KeyWordSearch
{
    public delegate void Mydelegate();
    public partial class Form1 : Form
    {
        string valid = @"[\u4E00-\u9FFF]+";
        public Form1()
        {
            InitializeComponent();
        }
        /*点击搜索一下按钮触发事件*/
        private void searchButton_Click(object sender, EventArgs e)
        {
            try
            {
                Task task_baidu = new Task(() => { Search_baidu("http://www.chinaso.com/newssearch/all/allResults?q=" + searchBox.Text); });
                Task task_bing = new Task(() => { Search_bing("https://cn.bing.com/search?form=MOZTSB&pc=MOZI&q=" + searchBox.Text); });
                task_baidu.Start();
                task_bing.Start();
            }
            catch (Exception) { }
        }
        // baidu
        private void Search_baidu(string url)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                WebResponse response = request.GetResponse();
                Stream resStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(resStream);
                string webInfo = sr.ReadToEnd();
                string webData = "";
                foreach (Match match in Regex.Matches(webInfo, valid))
                {
                    webData += match;
                }
                this.BeginInvoke(new Mydelegate(() =>
                {
                    baiduBox.Clear();
                    baiduBox.Text = webData.Substring(0, 200);

                }));
            }
            catch (Exception) { }
        }
        // bing
        private void Search_bing(string url)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                WebResponse response = request.GetResponse();
                Stream resStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(resStream);
                string webInfo = sr.ReadToEnd();
                string webData = "";
                foreach (Match match in Regex.Matches(webInfo, valid))
                {
                    webData += match;
                }
                this.BeginInvoke(new Mydelegate(() =>
                {
                    bingBox.Clear();
                    bingBox.Text = webData.Substring(0, 200);

                }));

            }
            catch (Exception) { }
        }
    }
}